package com.xuebusi.toutiao.admin.api.common.util;

import com.xuebusi.toutiao.admin.api.common.config.GlobalConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件操作工具类
 */
@Slf4j
@Component
public class FileUtil {
    private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd/");

    @Resource
    private GlobalConfig globalConfig;

    /**
     * 磁盘是否可读
     *
     * @param filePath
     * @return
     */
    public static boolean canRead(String filePath) {
        String[] split = filePath.split(":");
        if (split.length == 1) {
            return false;
        }
        String disk = split[0] + ":";
        boolean canRead = false;
        File[] roots = File.listRoots();
        for (File file : roots) {
            if (file.getPath().toUpperCase().startsWith(disk.toUpperCase()) && file.canRead()) {
                canRead = true;
                break;
            }
        }
        return canRead ? true : false;
    }

    /**
     * 上传文件到指定目录
     *
     * @param file       文件
     * @param request    请求
     * @param uploadPath 目录
     * @return 文件路径
     * @throws IOException
     */
    public static String upload(MultipartFile file, HttpServletRequest request, String uploadPath) throws IOException {
        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 比如：/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = DATE_FORMAT.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName;
        String uuid = UUID.randomUUID().toString().replace("-", "");
        if (oldName.contains(".")) {
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            newName = uuid + suffix;
        } else {
            newName = uuid + ".jpg";
        }

        // 文件保存
        file.transferTo(new File(folder, newName));
        // 返回上传文件的访问路径
        String filePath = "/" + format + newName;
        return filePath;
    }

    /**
     * 如期图片路径包含域名部分，就截取域名后面的部分
     *
     * @param imageUrl 图片完整URL地址
     * @return
     * @throws MalformedURLException
     */
    public String getRelativeImagePath(String imageUrl) {
        String webSite = globalConfig.getWebSite();
        if (imageUrl.startsWith(webSite)) {
            try {
                return new URL(imageUrl).getPath();
            } catch (MalformedURLException e) {
                log.error(">>> 图片URL格式解析错误:{}", imageUrl);
            }
        }
        return imageUrl;
    }
}
